package android.demo.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class HandlerActivity extends Activity {

	private final String TAG = "HandlerActivity";
	private Button btnStart;   
    private Button btnStop;  
    //创建Handler对象   
    Handler handler = new Handler();   

	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		LinearLayout layout = new LinearLayout(this);   
		layout.setOrientation(LinearLayout.VERTICAL);   

		btnStart = new Button(this);
		btnStop = new Button(this);
           
		btnStart.setId(100);
		btnStart.setText("启动");
		btnStart.setOnClickListener(new Button.OnClickListener() {   
  
            public void onClick(View arg0) {   
                /**  
                 * 调用Handler的post方法，将要执行的线程对象添加到线程队列中  
                 */  
                handler.post(updateThread);   
            }   
               
        }); 
		layout.addView(btnStart);
		
		btnStop.setId(200);
		btnStop.setText("停止");
		btnStop.setOnClickListener(new Button.OnClickListener() {   
  
            public void onClick(View v) {   
                handler.removeCallbacks(updateThread);   
            }   
        });  
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(250, 50);   
		param.topMargin = 10;   
		layout.addView(btnStop, param);
		setContentView(layout);       
    }   

	/**  
     * 将要执行的操作写入线程对象的run()方法当中  
     */  
    Runnable updateThread = new Runnable() {   
        public void run() {   
            Log.i(TAG, "更新线程");   
            //在run方法内部，执行postXX的方法，每隔3秒会执行一次   
            handler.postDelayed(updateThread, 3000);   
        }   
    };   

}
